/*
* wx
*/
import { APP_ID, GIZ_BASE_API } from '../config'
import _ from 'lodash'
const wxSdk = {
  init: function () {
    const request = wx.request;
    Object.keys(wx).forEach(key => {
      const tempFunc = wx[ key ];
      this[key] = tempFunc;
      if (_.isFunction(tempFunc) && !/Sync$/.test(key) && !/create/.test(key)) {
        Object.defineProperty(this, key, {
          value(config) {
            if(_.isFunction(config)){
              tempFunc(config)
              return false;
            }
            config = config || {};
            return new Promise(function (resolve, reject) {
              let success = config.success, fail = config.fail;
              config.success = function (result) {
                console.log(result)
                resolve(result)
                success && success(result)
              }
              config.fail = function (result) {
                console.log(result)
                resolve(result)
                fail && fail(result)
              }
              tempFunc(config)
            });
          },
          writable: true
        })
      }
    })
    Object.defineProperty(this, 'request', {
      value(config) {
        config = config || {};
        return new Promise(function (resolve, reject) {
          if (!/^http/.test(config.url)) {
            config.url = GIZ_BASE_API + config.url;
            config.header = Object.assign({
              'X-Gizwits-User-token': Store.state.login.token,
            }, config.header)
          }
          let success = config.success, fail = config.fail;
          config.header = Object.assign({
            'X-Gizwits-Application-Id': APP_ID,
          }, config.header)
          config.success = function (result) {
            success && success(result.data)
            resolve(result.data)
          }
          config.fail = function (result) {
            fail && fail(result)
            resolve(result)
          }
          request(config)
        });
      },
      writable: true
    })
    const showLoading = wx.showLoading;
    Object.defineProperty(this, 'showLoading', {
      value(config) {
        if (_.isObject(config)) {
          showLoading(config)
        } else {
          showLoading({
            title: config || '加载中...',
          })
        }
      }
    })
    const showToast = wx.showToast;
    Object.defineProperty(this, 'showToast', {
      value(config) {
        if (_.isObject(config)) {
          config.duration = config.duration || 3000,
          showToast(config)
        } else {
          showToast({
            title: config,
            icon: 'none',
            duration: 3000,
          })
        }
      }
    })
  }
};
export default wxSdk
